import { takeEvery, put } from 'redux-saga/effects'
import axios from 'axios'
function* login ({payload}) {
  try {
    let { data } = yield axios.post('/users/login', payload)
    localStorage.setItem('token', data.user.token)
    yield put({type: 'loginSuccess', payload: data.user})
  } catch (ex) {
    const errors = ex.response.data.errors
    const message = []
    for (let attr in errors) {
      errors[attr].forEach(mes => {
        message.push(`${attr} ${mes}`)
      })
    }
    yield put({type: 'loginFailed', payload: message})
  }
}

function* loadUser ({payload}) {
  try {
    let {data}  = yield axios.get('/user', {
      headers: {
        Authorization: `Token ${payload}`
      }
    })
    yield put({type: 'loadUserSuccess', payload: data.user})
  } catch (ex) {
    yield put({type: 'loadUserFailed', payload: []})
  }
  
}

export default function* authSaga () {
  yield takeEvery('login', login)
  yield takeEvery('loadUser', loadUser)
}